package com.example.erhuo.fragment;

import androidx.appcompat.widget.SearchView;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.app.Activity;
import android.content.Context;
import android.os.Binder;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.example.erhuo.R;

import com.example.erhuo.WantOrder;
import com.example.erhuo.adapter.WantOrderAdapter;
import com.example.erhuo.api.NetAPI;
import com.example.erhuo.databinding.MyFragmentBinding;
import com.example.erhuo.databinding.SellFragmentBinding;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.MaterialToolbar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.LinkedList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SellFragment extends Fragment {

    private SellViewModel mViewModel;
    private static String TAG = "SellFragment";
    private WantOrderAdapter adapter;
    private ListView listView;
    private Activity activity;
    private SellFragmentBinding binding;


    public static SellFragment newInstance() {
        return new SellFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mViewModel = ViewModelProviders.of(getActivity()).get(SellViewModel.class);

        binding = DataBindingUtil.inflate(inflater, R.layout.sell_fragment, container, false);
        binding.setData(mViewModel);
        binding.setLifecycleOwner(getActivity());
        adapter = new WantOrderAdapter(new LinkedList<>(), getContext());
        View root = binding.getRoot();
        listView = (ListView) root.findViewById(R.id.wantOrder_listView);
        getAllOrder(0, 20);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        listView.setAdapter(adapter);
        return root;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "onActivityCreated");
        activity = getActivity();
        mViewModel = new ViewModelProvider(this).get(SellViewModel.class);
        // TODO: Use the ViewModel
    }


    private void getAllOrder(int start, int num) {
        RequestBody body = new FormBody.Builder()
                .add("start", "" + start)
                .add("num", "" + num)
                .build();
        Callback callback = new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "获取求购列表失败");
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "获取求购列表失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String information = response.body().string();
                Log.i(TAG, information);
                JSONObject json;
                try {
                    json = new JSONObject(information);
                    String code = json.getString("code");
                    switch (code) {
                        case "200": {
                            Log.i(TAG, "获取所有商品成功");
                            JSONArray dataJson = json.getJSONObject("data").getJSONArray("requirelist");
                            for (int i = 0; i < dataJson.length(); i++) {
                                JSONObject object = dataJson.getJSONObject(i);
                                String id = object.getString("requireid");
                                String senderId = object.getString("requiresenderid");
                                String price = object.getString("requireprice");
                                String title = object.getString("requirename");
                                //String description = object.getString("requir")
                                //String status = object.getString("requriestatus");
                                WantOrder order = new WantOrder(id, senderId, price, title, null, null);
                                adapter.addWant(order);
                            }
                            Log.i(TAG, "现在有多少项：" + adapter.getCount());
                            binding.wantOrderListView.setAdapter(adapter);
                            break;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        NetAPI.postJson("api/RequireOper/searchAllRequire/", body, callback);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (getActivity() != null) {
            Log.i(TAG, "hahaha");
        }
        activity = getActivity();
    }
}